package com.cskaoyan.controller.backStage;

import com.cskaoyan.model.vo.BaseRespVO;
import com.cskaoyan.model.vo.ExceptionVO;
import com.cskaoyan.model.vo.InfoDataVO;
import com.cskaoyan.model.vo.LoginDataVO;
import com.cskaoyan.service.AdminService;
import com.cskaoyan.shiro.MallToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Map;


// 不授权
//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解
@RestController
@RequestMapping("admin/auth")
public class AuthController {


    @Autowired
    AdminService adminService;

    /**
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
    @PostMapping("login")
    public ExceptionVO login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        MallToken adminToken = new MallToken(username, password, "admin");
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(adminToken);
        } catch (AuthenticationException e) {
            return ExceptionVO.error(605, "用户名账号或者密码不正确");
        }
        LoginDataVO loginUserDataVO = adminService.getAdminInfoByName(username);
        loginUserDataVO.setToken((String) subject.getSession().getId());
        return BaseRespVO.ok(loginUserDataVO);

    }

    @GetMapping("401")
    public ExceptionVO redirect() {
        return ExceptionVO.fine();
    }

    @RequestMapping("info")
    /**
     * @author: lixiaosheng
     * @description: 根据权限展示页面
     * @date: 2022/5/8 19:01
     */
    public ExceptionVO info(String token) {

        Subject subject = SecurityUtils.getSubject();
        Serializable id = subject.getSession().getId();
        if (id.equals(token)) {
            String username = (String) subject.getPrincipals().getPrimaryPrincipal();
            InfoDataVO infoDataVO = adminService.getAdminPermissionInfoByName(username);
            return BaseRespVO.ok(infoDataVO);
        }
        return ExceptionVO.error("出现异常");

    }

    @PostMapping("logout")
    /**
     * @author: lixiaosheng
     * @description: 登出
     * @date: 2022/5/8 19:48
     */
    public ExceptionVO logout(HttpSession session) {
        session.invalidate();
        return ExceptionVO.fine();
    }
}
